package com.daxt.utils;

import java.io.File;

import com.amazonaws.AmazonServiceException;
import com.amazonaws.ClientConfiguration;
import com.amazonaws.Protocol;
import com.amazonaws.auth.AWSStaticCredentialsProvider;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.client.builder.AwsClientBuilder;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3ClientBuilder;
import com.amazonaws.services.s3.model.PutObjectResult;

public class OssUtil {

	// 测试环境
	public static String ENDPOINT = "http://127.0.0.1:9000/";
	public static String accessKey = "szlusername";
	public static String secretKey = "szlpassword";
	
	
	public static String upload(String bucketName, String fileName, File file) {
		try {
			AmazonS3 s3Client = OssUtil.init();
			OssUtil.Bucketvalidate(bucketName, s3Client);
			s3Client.putObject(bucketName, fileName, file);
			return bucketName+fileName;
		} catch (Exception e) {
			return null;
		}

	}
	
	public static boolean Bucketvalidate(String bucketName, AmazonS3 s3Client) {
		try {

			if (!s3Client.doesObjectExist(bucketName, "")) {
				s3Client.createBucket(bucketName);
			}
		} catch (AmazonServiceException e) {
			return false;
		}
		return true;
	}

	public static AmazonS3 init() {
		BasicAWSCredentials credentials = new BasicAWSCredentials(accessKey, secretKey);
		ClientConfiguration clientConfig = new ClientConfiguration();
		clientConfig.setSignerOverride("S3SignerType");
		clientConfig.setProtocol(Protocol.HTTP);
		AmazonS3 s3Client = AmazonS3ClientBuilder.standard()
				.withCredentials(new AWSStaticCredentialsProvider(credentials)).withClientConfiguration(clientConfig)
				.withEndpointConfiguration(new AwsClientBuilder.EndpointConfiguration(
						ENDPOINT,
						"cn-north-1"))
				.withPathStyleAccessEnabled(true)
				.build();
		return s3Client;
	}


}
